import datetime

from utils.render import json_detail_render
from webapp.extensions import AppException
from webapp.models import Room, db, ScheduleTable, VBorrowInfo, BorrowInfo
from webapp.service.board_service import BoardService


class RoomService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        roomname = kwargs.get('roomname')
        roomtype = kwargs.get('roomtype')
        not_empty = roomname or roomtype or create_times
        query = []
        if roomname:
            query.append((Room.roomname.like(f'%{roomname}%')))
        if roomtype:
            query.append(Room.roomtype == roomtype)
        if create_times and len(create_times) >= 2:
            query.append((Room.create_time.between(create_times[0], create_times[1])))
        result = Room.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                    error_out=False)
        return result

    @staticmethod
    def create(curr_room: Room):
        session = Room.query.filter(Room.roomname == curr_room.roomname).one_or_none()
        if session:
            raise AppException(f'{curr_room.session}已存在!')
        curr_room.create_time = datetime.datetime.now()
        db.session.add(curr_room)
        db.session.commit()

    @staticmethod
    def delete(room_set):
        if room_set:
            for room in room_set:
                db.session.delete(room)
            db.session.commit()

    @staticmethod
    def find_by_id(id):
        room = db.session.query(Room).filter(Room.id == id).one_or_none()
        if room is None:
            raise AppException(f'您所操作的对象已不存在!')
        return room

    @staticmethod
    def update(curr_room: Room):
        room = Room.query.filter(Room.id == curr_room.id).one_or_none()
        if room is None:
            raise AppException(f'修改的数据可能已不存在!')
        room.roomname = curr_room.roomname
        room.roomtype = curr_room.roomtype
        room.update_time = datetime.datetime.now()
        room.update_by = curr_room.update_by
        db.session.commit()

    @staticmethod
    def findempty(jsonData):
        weeknum = jsonData.get("weeknum")
        weekorder = jsonData.get("weekorder")

        session = BoardService.get_cur_session()
        emptyRoom = set()
        scheduleTables = ScheduleTable.query.filter(ScheduleTable.weekorder == weekorder,
                                                    ScheduleTable.sessionId == session.id,
                                                    ScheduleTable.weeknum == weeknum).all()
        borrrowInfos = VBorrowInfo.query.filter(VBorrowInfo.weekorder == weekorder,
                                                VBorrowInfo.sessionid == session.id,
                                                VBorrowInfo.weeknum == weeknum).all()
        for borrrowInfo in borrrowInfos:
            emptyRoom.add(borrrowInfo.resourceId)
        for scheduleTable in scheduleTables:
            emptyRoom.add(scheduleTable.placeId)
        rooms = Room.query.filter(Room.id.notin_(emptyRoom)).paginate(
            int(0) + 1, per_page=int(1000),
            error_out=False)
        return rooms

    @staticmethod
    def applyResource(data):
        resourceid = data.get("resourceid")
        weeknum = data.get("weeknum")
        weekorder = data.get("weekorder")
        rtype = data.get("rtype")
        start = data.get("start")
        end = data.get("end")
        borrower = data.get("borrower")
        resname = data.get("resname")
        session = BoardService.get_cur_session()
        borrowInfo: BorrowInfo = BorrowInfo.query.filter(BorrowInfo.resname == resname).one_or_none()
        if borrowInfo:
            return json_detail_render(1, message=f'{resname}已申请\n，请勿重复申请!')

        borrowInfo = BorrowInfo(
            resourceid=data.get("resourceid"),
            rtype=data.get("rtype"),
            resname=data.get("resname"),
            weeknum=data.get("weeknum"),
            weekorder=data.get("weekorder"),
            start=data.get("start"),
            end=data.get("end"),
            borrower=data.get("borrower"),
            sessionid=session.id,
            create_time=datetime.datetime.now()
        )
        db.session.add(borrowInfo)
        db.session.commit()
        return json_detail_render(0, message=f'申请成功')

    @classmethod
    def applyList(cls):
        borrowInfo = VBorrowInfo.query.paginate(
            int(0) + 1, per_page=int(1000),
            error_out=False)
        return borrowInfo
